<%--
  Created by IntelliJ IDEA.
  User: lirance
  Date: 15/5/17
  Time: 下午11:18
  To change this template use File | Settings | File Templates.
  进入的聊天室
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
    <title>欢迎进入聊天室${sessionScope.room.roomname}</title>
    <link rel="stylesheet" href="/css/chatting.css">
    <script src="http://libs.baidu.com/jquery/1.10.2/jquery.min.js">
    </script>
    <script>
        $(document).ready(function(){
            $("#flip").click(function(){
                $("#panel").slideToggle("100");
            });
        });
    </script>
    <style type="text/css">
        #panel{
            padding: 40px;
            display: none;
        }
        #panel
        {
            position: absolute;
            opacity: 0.5;
            top: 10em;
            left: 0em;
            width:71.9em;
        }
    </style>

</head>
<body>



<div id="panel">

    <!--
         弹出框效果，普通用户，房间成员列表，房主：更改房间名，撤销房间。
      -->
    <div id="changeroom">

        <s:iterator var="roomMember" value="RoomMemberLists">
            <button type="button" name="membername" class="button-membername">
                <s:property value="#roomMember.memberEntity.username"/>
            </button>
        </s:iterator>


        <s:if test="#session.user.id==#session.room.owner">
            <div id="changeroomname">
                <form action="ChagRoomName" method="post">
                    <span>房间名</span>
                    <input type="text" id="changeroomname-input" name="newRoomName"/> <br>
                    <button type="submit" id="changeroomname-button">修改房名</button>
                    <a href="DeleteRoom">
                        <button type="button" id="changeroomname-button1">撤销房间</button>
                    </a>
                    <a href="chatHistory">
                        <button type="button" id="changeroomname-button2">查看聊天记录</button>
                    </a>
                </form>
            </div>
        </s:if>
    </div>
</div>


<div id="head">
    <div id="title">
        <span id="span-style">${sessionScope.room.roomname}</span>
        <div id="flip">
            <img id="func-style" src="images/func.png"/>
        </div>
        <a href="ExitRoom"> <img id="logout-style" src="images/logout.png" width="20px" height="20px"/></a>
    </div>

    <div id="texteditor">
        <textarea name="content" id="content" ></textarea>
        <input type="button" id="post-button" onclick="sendMsg()" value="post" />
    </div>
</div>

<div id="chatBank">

    <!--<textarea name="showContent" id="showContent" rows="40" cols="80" readonly style="overflow:auto"></textarea>-->
    <div name="showContent" id="showContent" rows="40" cols="80" readonly style="overflow:auto"></div>

</div>


<div id="warning" style="color:red"></div>


<script language="javascript" type="text/javascript">
    String.prototype.format = function () {
        var args = arguments;
        return this.replace(/\{(\d+)\}/g,
                function (m, i) {
                    return args[i];
                });
    }
    var xmlHttp = false;
    var xmlHttpTimer;
    var lastLoad = new Date().valueOf();
    if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
        xmlHttp = new XMLHttpRequest();
        xmlHttpTimer = new XMLHttpRequest();
    }
    else { // code for IE6, IE5
        xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
        xmlHttpTimer = new ActiveXObject("Microsoft.XMLHTTP");
    }
    //初始化聊天记录
    var url = "/initChatHistories.action?roomid=${sessionScope.room.id}";
    xmlHttp.open("GET", url, true);
    xmlHttp.onreadystatechange = initValue;
    xmlHttp.send(null);

    function formatContentsValueByUC(username,content)
    {
        var str = "<div class=\"onememchatstyle\">"+
                "<div class=\"touxianghenamestyle\">"+
                "<div class=\"touxiang-style\">"+
                "<img src=\"images/TouXiang/1.png\" class=\"left-style\"/>"+
                "</div>"+
                "<div class=\"chatname-style\">"+
                "<label class=\"select-name\">"+
                "{0}"+
                "</label>"+
                "</div>"+
                "</div>"+
                "<div class=\"contentstyle\">"+
                "<p class=\"body1 select-text1\" style=\"position: relative;left: 20%;top: -3.5em\" >"+
                "{1}"+
                "</p>"+
                "</div>"+
                "</div>\n"
        return str.format(username, content);
    }

    function formatContentsValue(jsonObjItem) {
        return formatContentsValueByUC(jsonObjItem.username,jsonObjItem.content);
    }
    function initValue() {
        if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
            var response = xmlHttp.responseText;
            var jsonObj = eval("(" + response + ")");
            lastLoad = jsonObj.lastLoad;
            var contents = document.getElementById("chatBank");
            var contentsValue = "";
            var chatHistories = jsonObj.chatHistories;
            for (var i = 0; i < chatHistories.length; ++i) {
                contentsValue = formatContentsValue(chatHistories[i]) + contentsValue;
            }
            contents.innerHTML += contentsValue;
        }
    }
    //每隔1s从服务器端接受数据
    var refreshInt = setInterval(refresh, 2000);
    window.onunload = function(){clearInterval(refreshInt);}
    //发送数据的需要修改
    function sendMsg() {
        var contents = document.getElementById("content").value;
        if (contents == "") {
            //alert("请输入聊天信息！");
            document.getElementById("warning").innerHTML = "请聊天输入信息！"
            //  document.content.focus();
            return false;
        }
        else {
            var url = "/sendChatHistories.action?content={0}&timestamp={1}&roomid={2}&userid={3}".format(contents, new Date().valueOf(), ${sessionScope.room.id}, ${sessionScope.user.id});
            xmlHttp.open("GET", url, true);
            //    xmlHttp.onreadystatechange = updatePage;
            xmlHttp.send(null);
            var showContent = document.getElementById("chatBank");
            document.getElementById("content").value = "";//清空输入框。
            showContent.innerHTML = formatContentsValueByUC('${sessionScope.room.ownerUserEntity.username}',contents) + showContent.innerHTML;
        }
    }
    /*
    function updatePage() {
        if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
            var response = xmlHttp.responseText;
            document.getElementById("content").value = "";//清空输入框。
            document.getElementById("warning").innerHTML = "";
            document.getElementById("chatBank").value += response;
           // alert(response);
        }
    }*/
    //从服务器端刷新数据
    function refresh() {
        var url = "/getChatHistories.action?lastLoad={0}&roomid={1}".format(lastLoad, ${sessionScope.room.id});
        xmlHttp.open("GET", url, true);
        xmlHttp.onreadystatechange = refreshChatHistory;
        xmlHttp.send(null);
    }
    function refreshChatHistory() {
        if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
            var response = xmlHttp.responseText;
            //alert(response);
            addItems(eval("(" + response + ")"));
        }
    }
    function addItems(itemsObj) {
        lastLoad = itemsObj.lastLoad;
        //遍历聊天记录
        for (var itemObj in itemsObj["chatHistories"]) {
            addItem(itemsObj["chatHistories"][itemObj]);
        }
    }
    function addItem(itemObj) {
        var contents = document.getElementById("chatBank");
        //添加的数据格式：<div>....</div>
        var newDiv = document.createElement("div");
        var spanUserName = document.createElement("span");
        spanUserName.name = "username";
        spanUserName.innerHTML = itemObj["username"];
        var content = document.createElement("span");
        content.name = "content";
        content.innerHTML = itemObj["content"];
        var time = document.createElement("span");
        time.name = "time";
        time.innerHTML = timestampformat(itemObj["time"]);
        contents.innerHTML = formatContentsValue(itemObj) + contents.innerHTML;
        /*
         newDiv.appendChild(spanUserName);
         newDiv.appendChild(content);
         newDiv.appendChild(time);
         contents.appendChild(newDiv);
         */
    }
    Date.prototype.format = function (format) {
        var o = {
            "M+": this.getMonth() + 1,        // month
            "d+": this.getDate(),        // day
            "h+": this.getHours(),        // hour
            "m+": this.getMinutes(),        // minute
            "s+": this.getSeconds(),        // second
            "q+": Math.floor((this.getMonth() + 3) / 3),        // quarter
            "S": this.getMilliseconds()        // millisecond
        };
        if (/(y+)/.test(format) || /(Y+)/.test(format)) {
            format = format.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
        }
        for (var k in o) {
            if (new RegExp("(" + k + ")").test(format)) {
                format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));
            }
        }
        return format;
    };
    function timestampformat(timestamp) {
        return (new Date(timestamp * 1000)).format("yyyy-MM-dd hh:mm:ss");
    }
</script>
</body>
</html>